<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-29 11:07:29
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-18 14:43:16
-->
<template>
	<div>
		<el-popover
			:visible="selection"
			:teleported="true"
			:placement="auth.accessOldman ? 'right' : 'bottom'"
			:width="auth.accessOldman ? 400 : 220"
			style="inset: auto 11% 68% !important"
		>
			<p>
				<el-icon>
					<InfoFilled />
				</el-icon>
				{{ popTitle }}
			</p>
			<el-progress v-if="visibleLoading" :percentage="percentage" />
			<div class="flex tr mt10" style="flex-flow: row wrap; gap: 10px">
				<el-button size="small" v-auth="auth.delete" v-show="!noMulDel" text @click="handleMulitDelete"> 选择删除 </el-button>
				<el-button size="small" v-auth="auth.export" type="primary" @click="handleMulitExport">
					{{ visibleLoading ? '正在执行导出...' : '选择导出' }}
				</el-button>
				<el-button size="small" :disabled="visibleLoading" v-if="auth.accessOldman" type="primary" @click="toOtherExport('report')">
					导出报告
				</el-button>
				<el-button size="small" :disabled="visibleLoading" v-if="auth.accessOldman" type="primary" @click="toOtherExport('word')">
					导出为word
				</el-button>
				<el-button size="small" :disabled="visibleLoading" v-auth="auth.subsidy_report" type="primary" @click="toOtherExport('subsidy_report')">
					导出为表格详情
				</el-button>
			</div>
			<template #reference>
				<el-button @click="handleMoreSet">
					<el-space wrap>
						<icon-application-menu theme="outline" />
						{{ !selection ? '批量操作' : '取消批量操作' }}
					</el-space>
				</el-button>
			</template>
		</el-popover>

		<el-dialog v-model="dialogVisible" append-to-body :title="dialogTitle" width="30%">
			<p class="text-gray">请选择您要导出的数据内容</p>
			<el-checkbox-group v-model="checkTopic">
				<el-checkbox v-for="(item, index) in exportMqTopic" :key="index" :value="item.topic" :label="item.label"> </el-checkbox>
			</el-checkbox-group>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleExport"> 导出 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { InfoFilled } from '@element-plus/icons-vue'
import { useConfigStore } from '@/stores/common'
import { getStore } from '@/utils/store'
import FileSaver from 'file-saver'
import useMqtt from '@/hooks/useMqttHooks'
import { onDownloadFile, DowloadPreviewImage } from '@/utils/util'
const { startMqtt, doUnSubscribe } = useMqtt()
const { setTableSelection } = useConfigStore()
const { selection } = storeToRefs(useConfigStore())

type Props = {
	exportMqTopic?: any
	exportApi?: string
	rowKey: string
	businessRowKey?: string
	paramsObj?: any
	multipleSelection: any
	auth?: any
	api?: any
	noMulDel?:boolean
}
const props = withDefaults(defineProps<Props>(), {
	noMulDel:false
})
const popTitle = ref('勾选数据')
const percentage = ref(0)
const visibleLoading = ref(false)
const dialogVisible = ref(false)
const checkTopic = ref([])
const dialogTitle = ref('操作')
const emit = defineEmits(['delete', 'cancel', 'refresh'])
const handleMulitDelete = () => {
	if (props.multipleSelection.length > 0) {
		emit('delete', 'delete', props.multipleSelection, '删除')
		emit('refresh')
	}
}

const startExport = (exportMqTopic) => {
	const userInfo = getStore('userInfo') || {}
	startMqtt(userInfo.id + exportMqTopic, async (topic, message) => {
		const msg = JSON.parse(message.toString())
		console.log(topic, msg, '*****导出消息*****')
		if (msg.progress == 'read') {
			percentage.value = msg.count
		}
		if (msg.progress == 'end' || msg.message == 'end') {
			if (topic.includes('orgSubsidy')) {
				window.open(msg.url, '_blank')
				visibleLoading.value = false
				return
			}
			if (msg.url.includes(':443/ningxiang')) {
				const previewUrl = (await DowloadPreviewImage(msg.url, 'blob')) as string
				const name = decodeURIComponent(msg.url).split('/')
				FileSaver.saveAs(previewUrl, name.slice(-1))
				return
			}

			setTimeout(() => {
				visibleLoading.value = false
				onDownloadFile(msg.url)
				emit('cancel')
			}, 100)
		}
	})
}
// 订阅导出主题
startExport('/ning/export/#')

const exportRequest = () => {
	let querySearch = {
		...props.paramsObj,
		pageParaPO: undefined,
		current: undefined,
		size: undefined,
		total: undefined,
	}
	const data = props.multipleSelection.map((item) => item[props.businessRowKey || props.rowKey])
	if (props.exportApi) {
		let queryObj = {
			...querySearch,
		}
		if (JSON.stringify(querySearch) !== '{}' || data.length > 0) {
			// 如何条件只有一个code 移除条件
			if (!(Object.values(querySearch).filter(Boolean).length == 1 && props.paramsObj.code) || data.length > 0) {
				queryObj.queryCondition = {
					...querySearch,
					idList: data,
				}
			}
		}
		if (Array.isArray(props.exportMqTopic)) {
			props.exportMqTopic
				.map((item, index) => {
					if (checkTopic.value.includes(item.topic)) {
						queryObj[item.po] = {
							...querySearch,
							code: item.code,
						}
					}
				})
				.filter(Boolean)
		} else if (data.length > 0) {
			queryObj.idList = data
		}

		apiMod[props.exportApi](queryObj)
			.then(() => {
				visibleLoading.value = true
				dialogVisible.value = false
				setTableSelection()
			})
			.catch((err) => {
				visibleLoading.value = false
			})
	}
}
// 一站办，老年人能力评估，补贴word,去其他导出
const toOtherExport = async (type: any) => {
	visibleLoading.value = true
	if (props.multipleSelection.length > 0) {
		let list = props.multipleSelection.map((res) => {
			const v = res.assessCode || res.applyNo || res.applyNos
			return v ? v.split(',') : []
		})
		const dataList = [].concat.apply([], list)
		if (type == 'subsidy_report') {
			// 报表导出.zip
			if (!props.api.subsidy_report) {
				return
			}
			apiMod[props.api.subsidy_report](dataList).then(async (res) => {
				const data = res.data
				visibleLoading.value = false
        handleMoreSet()
				if (data) {
					const previewUrl = (await DowloadPreviewImage(data.url || data, 'blob')) as string
					FileSaver.saveAs(previewUrl, `${data.name}.zip` || '补贴报表详情.zip')
				}
				// if(res.data) window.open(res.data,'_blank')
			})
		} else if (type == 'report') {
			apiMod.view_export_excel({ assess_code: dataList }).then((res) => {
				visibleLoading.value = false
         handleMoreSet()
				FileSaver.saveAs(res, '评估记录报告.zip')
			})
		} else {
			apiMod.view_export_word({ assess_code: dataList }).then((res) => {
				visibleLoading.value = false
        handleMoreSet()
				FileSaver.saveAs(res, '评估记录word.zip')
			})
		}
	} else {
		ElMessage.warning('请勾选您要导出的数据内容')
	}
}
const handleExport = () => {
	// doUnSubscribe()
	// 批量订阅
	exportRequest()
}
const handleMulitExport = () => {
	if (props.multipleSelection.length == 0) {
		ElMessage.warning('请勾选您要导出的数据内容')
		return
	}
	if (Array.isArray(props.exportMqTopic)) {
		dialogVisible.value = true
		dialogTitle.value = `导出 ${props.multipleSelection.length} 名服务对象`

		checkTopic.value = props.exportMqTopic.map((item) => item.topic)
		return
	}
	exportRequest()
}
const handleMoreSet = () => {
	setTableSelection()
	if (selection.value == false) {
		emit('cancel')
	}
}
onUnmounted(() => {
	doUnSubscribe()
})

watch(
	() => props.multipleSelection,
	(val) => {
		popTitle.value = `已选择 ${val.length} 条数据`
	},
	{
		immediate: true,
		deep: true,
	}
)
</script>

<style scoped></style>
